//
//  PlayManager.m
//  first app
//
//  Created by 林 小明 on 14-7-10.
//
//

#import "PlayManager.h"
#import "FileCenter.h"

@implementation PlayManager

+ (PlayManager *)sharedSingleton
{
    static PlayManager *sharedSingleton;
    
    @synchronized(self)
    {
        if (!sharedSingleton)
            sharedSingleton = [[PlayManager alloc] init];
        
        return sharedSingleton;
    }
}

- (PlayManager *)init
{
    //后台播放音频设置
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    //让app支持接受远程控制事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    playlist = [[NSMutableArray alloc] initWithCapacity:20];
    playStatusInfos = [[NSMutableDictionary alloc] init];
    currentpos = -1;
    return [super init];
}

- (BOOL) setPlayList:(NSMutableArray*)list
{
    [playlist removeAllObjects];
    [playlist addObjectsFromArray:list];
    return YES;
}

- (BOOL) startPlay:(int)pos
{
    if (player.playing)
    {
        return NO;
    }
    
    NSUInteger playlistCount = [playlist count];
    if ( playlistCount > 0 && pos >= 0 && pos < playlistCount )
    {
        currentpos = pos;
        NSDictionary *playInfo = [playlist objectAtIndex:currentpos];
        NSString* dirname = [playInfo objectForKey:@"dir"];
        NSString* filename = [playInfo objectForKey:@"name"];
        //NSString* filedesc = [playInfo objectForKey:@"desc"];
        
        NSData* data = [FileCenter ReadFile:dirname fileName:filename];
        
        player = [[AVAudioPlayer alloc] initWithData:data error:nil];
        [player setDelegate:self];
        
        [player play];
        [self notificationPlayStatus:PlayerStatusPlay URL:[playInfo objectForKey:@"url"]];
        
        return YES;
    }
    
    return NO;
}

- (void) startPlay
{
    if (!player.playing)
    {
        [player play];
        NSDictionary *playInfo = [playlist objectAtIndex:currentpos];
        [self notificationPlayStatus:PlayerStatusResume URL:[playInfo objectForKey:@"url"]];
    }
}

- (void) stopPlay
{
    if (player.playing)
    {
        [player stop];
        NSDictionary *playInfo = [playlist objectAtIndex:currentpos];
        [self notificationPlayStatus:PlayerStatusStop URL:[playInfo objectForKey:@"url"]];
    }
}

- (BOOL) isPlaying
{
    return player.playing;
}

- (BOOL) isInit
{
    return currentpos==-1;
}

- (void) setCurrentTime:(NSTimeInterval)time
{
    return [player setCurrentTime:time];
}

- (NSTimeInterval) getCurrentTime
{
    return player.currentTime;
}

- (NSTimeInterval) getDuration
{
    return player.duration;
}

- (NSString *) getTitle
{
    if ( currentpos < 0 )
    {
        return @"";
    }
    
    return [[playlist objectAtIndex:currentpos] objectForKey:@"desc"];
}

- (NSString *) getURL
{
    if ( currentpos < 0 )
    {
        return @"";
    }
    
    return [[playlist objectAtIndex:currentpos] objectForKey:@"url"];
}

- (void) notificationPlayStatus:(int)play_status URL:(NSString*)url;
{
    [playStatusInfos setValue:[NSNumber numberWithInt:play_status]
                    forKey:@"status"];
    [playStatusInfos setValue:url
                    forKey:@"url"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_Playstatus" object:playStatusInfos userInfo:nil];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)aplayer successfully:(BOOL)flag
{
    if (aplayer == self->player && flag == YES)
    {
        NSDictionary *playInfo = [playlist objectAtIndex:currentpos];
        [self notificationPlayStatus:PlayerStatusStop URL:[playInfo objectForKey:@"url"]];

        currentpos++;
        NSUInteger playlistCount = [playlist count];
        if ( playlistCount > 0 && currentpos >= 0 && currentpos < playlistCount )
        {
            [self startPlay:currentpos];
        }
        else
        {
            currentpos = 0;
        }
    }
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error
{
    NSLog(@"audio decode error." );
}
- (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player
{
}
- (void)audioPlayerEndInteruption:(AVAudioPlayer*)player
{
}

@end
